<template>
  <div class="container">

    <!-- 添加用户按钮和搜索框 -->
    <div class="search-container">
      <el-input v-model="searchKeyword" placeholder="搜索员工" clearable @keyup.enter.native="searchUsers"
                class="search-input"></el-input>
    </div>
    <!-- 使用 Element UI 的表格组件 -->
    <el-table :data="filteredData" style="width: 100%">
      <el-table-column prop="eid" label="员工编号"></el-table-column>
      <el-table-column prop="ename" label="员工名字"></el-table-column>
      <el-table-column prop="pid" label="项目类型">
        <template slot-scope="scope">
          {{ scope.row.pid === 1 ? '美容項目' : '美发项目' }}
        </template>
      </el-table-column>
      <el-table-column prop="tid" label="技术类型">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ meirongList.find(item => item.tid === scope.row.tid).tname }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="money" label="价格"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="addAppoint(scope.row)">预约</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="预约" :visible.sync="isAppoint" width="50%" :before-close="closeAppoint">
      <el-form label-width="120px" :model="appointForm">
        <div style="margin:20px;height:100%;float:left;">
          <div style="display:flex;justify-content:space-between;">
        <span v-for="(item,index) in week" :key="index"
              :class="{'top_style':item.is_active==0,'top_active':item.is_active==1}" @click="changWeek(item,index)">
          <div style="height:25px;line-height:20px;">{{ item.month }}-{{ item.date }}</div>
          <div style="height:25px;line-height:20px;">{{ item.day }}</div>
        </span>
          </div>
          <div style="display:flex;margin:20px 50px;font-size:18px;justify-content:space-between;">
            <div style="display:flex;">
              <div style="background-color:#C8C9CC;width:40px;height:20px;margin-right:10px;"></div>
              <div>不可预约</div>
            </div>
            <div style="display:flex;">
              <div style="background-color:#ffa4a4;width:40px;height:20px;margin-right:10px;"></div>
              <div>已有预约</div>
            </div>
            <div style="display:flex;">
              <div style="background-color:#3EA7F1;width:40px;height:20px;margin-right:10px;"></div>
              <div>当前预约</div>
            </div>
          </div>
          <div style="margin:20px 50px;height:100%;display: flex; justify-content: space-between; align-content: center;" class="button_wrap">
            <el-button
              v-for="(item, index) in timeArr"
              :key="index"
              @click="changTime(item, index)"
              :type="item.status == 0 ? '' : item.status == 1 ? 'danger' : item.status == 2 ? 'info' : item.status == 3 ? 'primary' : 'default'"
              :disabled="item.status == 1 || item.status == 2"
              class="button_style"
            >
              {{ item.time }}
            </el-button>
          </div>
          <div style="display: flex; flex-direction: column; justify-content: space-between; align-content: center;">
            <div style="display:flex;justify-content:flex-start;margin-left:50px;">
              <div style="width:80px;line-height:36px;height:36px;">备注：</div>
              <el-input style="width:100%;" placeholder="请输入" v-model="remark" clearable></el-input>
            </div>
            <div style="margin-top: 10px;">
              <el-radio-group v-model="rechargeParams.paymentType" @change="paymentTypeChange">
                <el-radio v-if="role == 0" border label="1">支付宝</el-radio>
                <el-radio v-if="role == 1" border label="2">余额</el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer" :style="{ height: '300px', lineHeight: '500px' }">
        <el-button @click="closeAppoint">取消</el-button>
        <el-button type="primary" @click="saveAppoint" style="margin-left:20px;">确定</el-button>
      </div>
    </el-dialog>


    <!-- 使用 Element UI 的分页组件 -->
    <el-pagination
      background
      layout="prev, pager, next"
      :total="pagebean.total"
      :page-size="pagebean.pagesize"
      :current-page="pagebean.pagenow"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>

<script>
import axios from 'axios';
import qs from 'qs';

export default {
  data() {
    return {
      reservation: {},
      pagebean: {
        total: 0,
        pagesize: 2,
        pagenow: 1,
        data: []
      },
      rechargeParams: {
        "totalAmt": '', //金额
        "paymentType": (JSON.parse(localStorage.getItem("user")).role + 1).toString(), //支付方式[0:微信,1:支付宝,2:余额,3:活动]
        "transType": "0" //交易类型[0:充值,1:消费]
      },
      meirongList: [],
      chooseEmp: {},
      addDialogVisible: false, // 控制添加用户对话框的显示与隐藏
      searchKeyword: '', // 存储搜索关键词
      filteredData: [], // 存储过滤后的数据
      fileList: [], // 存储上传文件列表
      isAppoint: false, appointForm: {},
      week: [],//预约周
      timeArr: [],
      dateNow: '',//预约日期
      timeStart: '',//预约时间
      timeEnd: '',//预约时间
      appointAreaId: '',//预约的会议室id
      rid: '',
      appointAreaName: '',//预约的会议室name
      positionId: '',//位置id
      positionName: '',//位置name
      remark: '',//备注
      appointTimeArr: [],//预约选中时间数组
      role: JSON.parse(localStorage.getItem("user")).role
    };
  },
  created() {
    this.doload();
  },
  methods: {
    handleCurrentChange(val) {
      this.pagebean.pagenow = val;
      this.doload();
    },
    doload() {
      const that = this;
      this.$axios.get(`http://localhost:9990/empfirstmeirong/${this.pagebean.pagenow}/${this.pagebean.pagesize}`)
        .then(response => {
          that.pagebean = response.data;
          that.filteredData = response.data.data; // 初始化过滤后的数据
        });
      this.searchTechnology();
    }, dosave() {
      const that = this;
      this.$axios.post('http://localhost:9990/reservation', qs.stringify(this.reservation))
        .then(() => {
          that.doload();
          that.reservation = {};
          that.addDialogVisible = false; // 关闭对话框
        });
    }, showAddDialog() {
      this.reservation = {}; // 清空表单
      this.addDialogVisible = true; // 显示对话框
    },
    dosaveLog() {
      const that = this;
      // console.log("this.reservation=========startTime",this.this.appointForm.startTime);
      // console.log("this.reservation=========rtime",this.reservation.rtime);
      console.log("this.reservation=========", this.reservation);
      this.reservation.menuname = "高级美容师";
      this.reservation.uname = localStorage.getItem("uname");
      this.reservation.money = this.chooseEmp.money;
      this.reservation.uid = JSON.parse(localStorage.getItem("user")).uid;
      this.reservation.eid = this.chooseEmp.eid;
      this.reservation.tid = this.chooseEmp.tid;
      this.reservation.pid = this.chooseEmp.pid;
      this.reservation.way = this.rechargeParams.paymentType;
      this.$axios.post('http://localhost:9990/reservationLog', qs.stringify(this.reservation))
        .then((res) => {
          // that.doload();
          that.reservation = {};
          that.addDialogVisible = false; // 关闭对话框
          //支付方式跳转
          if (this.rechargeParams.paymentType == '1') {
            // that.$message.success('支付宝支付')
            // 进行支付宝跳转
            const div = document.createElement('div')
            /* 下面的data.content就是后台返回接收到的数据 */
            div.innerHTML = res.data
            document.body.appendChild(div)
            document.forms[1].setAttribute('target', '_blank')
            document.forms[1].submit();
            const parent = div.parentNode;
            if (parent) {
              parent.removeChild(div);
            }
          } else if (this.rechargeParams.paymentType == '2') {
            if (res.data == "success") {
              this.$message.success('余额支付成功');
            } else {
              this.$message.error('余额支付失败，请去充值会员卡');
            }
          } else {
            this.$message.success('活动支付')
          }
        });
    },
    searchUsers() {
      // 过滤数据
      this.filteredData = this.pagebean.data.filter(emp => {
        return (
          emp.ename.includes(this.searchKeyword) ||
          emp.esex.includes(this.searchKeyword) ||
          emp.eage.includes(this.searchKeyword) ||
          emp.ephone.includes(this.searchKeyword) ||
          emp.tid.includes(this.searchKeyword) ||
          emp.lid.includes(this.searchKeyword) ||
          emp.money.includes(this.searchKeyword) ||
          emp.photos.includes(this.searchKeyword)
        );
      });
    }, handleSelectionChange(val) {
      console.log(val);
      this.selectList = val;
    },
    handleEdit(val) {
      console.log(val, "编辑");
    },
    handleDelete(val) {
      console.log(val, "删除");
    },
    //定义导出表格的文件名、表头和字段
    // exportPeopleScoreExcel() {
    //   this.exportList = this.selectList;
    //   this.tableTitle = "人员统计";
    //   this.tableHeader = ["姓名", "日期", "地址"];
    //   this.filterVal = ["name", "date", "address"];
    // },
    closeAppoint() {
      this.isAppoint = false
      for (let i = 0; i < this.week.length; i++) {
        this.week[i].is_active = 0;
      }
      this.week[0].is_active = 1;
      this.remark = '';
      for (let i = 0; i < this.timeArr.length; i++) {
        if (this.timeArr[i].status == 3) {
          this.timeArr[i].status = 0;
        }
      }
    },
    saveAppoint() {
      console.log("this.timeStart ", this.timeStart)
      console.log("this.timeEnd ", this.timeEnd)
      if (this.timeStart != '' && this.timeEnd != '') {
        this.appointForm.appointAreaId = this.appointAreaId;
        this.appointForm.appointAreaName = this.appointAreaName;
        this.appointForm.positionId = this.positionId;
        this.appointForm.positionName = this.positionName;
        this.appointForm.remark = this.remark;
        this.appointForm.rid = this.rid;
        this.appointForm.startTime = this.dateNow + ' ' + this.timeStart;
        this.appointForm.endTime = this.dateNow + ' ' + this.timeEnd;
        //
        // appoint(this.appointForm).then(res=>{
        //   if(res.data.code==200){
        //     this.$message.success(res.data.message)
        //     this.remark='';
        //     this.isAppoint=false;
        //     this.isMeeting=false
        //     this.getList();
        //   }else{
        //     this.$message.error(res.data.message)
        //   }
        // })
        // 保存数据，成功后，关闭弹窗，并且再去调用一次获取列表的接口
        console.log(this.appointForm)
        this.$message.success('预约成功!!!')
        this.remark = '';
        this.isAppoint = false;
        this.reservation.timerange = this.appointForm.startTime;
        this.reservation.pid = this.appointForm.rid;
        this.dosaveLog();


      } else {
        this.$message.error("请选择预约时间")
        // return ;
        for (let i = 0; i < this.timeArr.length; i++) {
          if (this.timeArr[i].status == 2) {
            this.timeArr[i].status = 0
          }
        }
      }
    },
    changTime(val, index) {
      if (this.timeArr[index].status === 3) {
        // 如果当前点击的时间已经选中，再次点击取消选择
        this.timeArr[index].status = 0;
        this.appointTimeArr = [];
        this.timeStart = '';
        this.timeEnd = '';
      } else {
        // 清空以前的选择
        for (let i = 0; i < this.timeArr.length; i++) {
          if (this.timeArr[i].status === 3) {
            this.timeArr[i].status = 0;
          }
        }

        // 记录新选择的时间
        this.timeArr[index].status = 3;
        this.appointTimeArr = [index];
        this.timeStart = this.timeArr[index].time;
        this.timeEnd = this.timeArr[index].time;
      }
    },

    // changTime(val,index){
    //   console.log("changTime==",val,index);
    //   if(this.appointTimeArr.length<2){
    //     this.timeArr[index].status=3;
    //     this.appointTimeArr.push(index);
    //     if(this.appointTimeArr.length==2){
    //       if(this.appointTimeArr[0]==this.appointTimeArr[1]){
    //         this.timeArr[this.appointTimeArr[0]].status=0;
    //         this.appointTimeArr=[];
    //       }else{
    //         this.appointTimeArr=this.appointTimeArr.sort(function(a,b){return a-b});
    //         let len=this.appointTimeArr[1]-this.appointTimeArr[0];
    //         for(let i=0;i<len;i++){
    //           if(this.timeArr[this.appointTimeArr[0]+i].status==1){
    //             this.$message.warning("已预约过的时间不允许预约！")
    //             this.timeStart='';
    //             this.timeEnd='';
    //             break
    //           }else{
    //             this.timeArr[this.appointTimeArr[0]+i].status=3;
    //             this.timeStart=this.timeArr[this.appointTimeArr[0]].time;
    //             this.timeEnd=this.timeArr[this.appointTimeArr[1]].time;
    //           }
    //         }

    //       }
    //     }
    //   }else if(this.appointTimeArr.length=3){
    //     for(let i=0;i<this.timeArr.length;i++){
    //       if(this.timeArr[i].status===3){
    //         this.timeArr[i].status=0;
    //       }
    //     }
    //     this.appointTimeArr=[];
    //     this.appointTimeArr.push(index);
    //     this.timeArr[index].status=3;
    //   }
    // },
    //每次打开预约弹窗时，默认选中当天
    getAppoint() {
      let arr = []
      for (let i = 0; i < 7; i++) {
        arr.push(this.dealTime(i))
      }
      arr[0].is_active = 1;
      this.week = arr;
      this.dateNow = this.week[0].full;
    },
    //点击切换星期状态
    changWeek(val, index) {
      for (let i = 0; i < this.week.length; i++) {
        this.week[i].is_active = 0;
      }
      this.week[index].is_active = 1;
      let formData = {
        appointAreaId: this.appointAreaId,
        startTime: val.full + ' ' + '00:00:00',
        endTime: val.full + ' ' + '23:59:59'
      };
      this.dateNow = val.full;
      this.getAppointed(formData)
    },
    // 处理未来七天的函数
    dealTime(num) {
      let time = new Date() // 获取当前时间日期
      let date = new Date(time.setDate(time.getDate() + num)).getDate() //这里先获取日期，在按需求设置日期，最后获取需要的
      let newDate = (date.toString()).padStart(2, "0");
      let month = time.getMonth() + 1 // 获取月份
      let newMonth = (month.toString()).padStart(2, "0");
      let day = time.getDay() //  获取星期
      let year = time.getFullYear();
      let full = year + '-' + month + '-' + date;
      switch (day) { //  格式化
        case 0:
          day = "星期日"
          break
        case 1:
          day = "星期一"
          break
        case 2:
          day = "星期二"
          break
        case 3:
          day = "星期三"
          break
        case 4:
          day = "星期四"
          break
        case 5:
          day = "星期五"
          break
        case 6:
          day = "星期六"
          break
      }
      let obj = {
        date: newDate,
        day: day,
        is_active: 0,
        month: newMonth,
        year: year,
        full: full,
      }
      return obj // 返回对象
    },
    //时间格式转为年月日
    getYMD(time) {
      let date = new Date(time)
      let Str = date.getFullYear() + '-' +
        (date.getMonth() + 1) + '-' +
        date.getDate()
      return Str
    },
    //预约
    addAppoint(val) {
      console.log("val=", val)
      //先写假的appointAreaId,appointAreaName,positionId,positionName
      this.chooseEmp = val;
      let appointAreaId = 123;
      let appointAreaName = '会议室1';
      let positionId = '11';
      let positionName = '2楼101';
      this.isAppoint = true;
      this.rid = val.pid;
      this.appointAreaId = appointAreaId;
      this.appointAreaName = appointAreaName;
      this.positionId = positionId;
      this.positionName = positionName;
      this.getAppoint();
      let formData = {
        appointAreaId: val.appointAreaId,
        startTime: this.getYMD(new Date()) + ' ' + '00:00:00',
        endTime: this.getYMD(new Date()) + ' ' + '23:59:59'
      }
      this.getAppointed(formData);
    },
    //获取时间数组
    getAppointed(formData) {
      console.log("formData---", formData)
      //假设当前时间是10:30，则10:30之前的时间点都是过期的，即状态是2；
      // 已经预约过的时间点是13:00，13:30，14:00，即状态是1
      let data = [
        {time: "5:00-7:00", status: 2},
        {time: "8:00-10:00", status: 0},
        {time: "11:00-12:30", status: 0},
        {time: "14:00-16:00", status: 0},
        {time: "16:30-22:00", status: 0},
      ];//写一组假数据
      let menuname = '高级美容师';
      console.log("week", this.week);
      this.$axios.get(`http://localhost:9990/reservationLog/${this.rid}/${menuname}`)
        .then(reservations => {
          console.log(reservations);
          reservations.data.forEach(reservation => {
            if (formData.startTime.split(' ')[0] === reservation.timerange.split(' ')[0]) {
              let reservationTime = reservation.timerange.split(' ')[1];
              data.forEach(item => {
                if (item.time === reservationTime) {
                  item.status = 1; // 将 status 修改为 3 表示匹配成功（可以根据需求更改）
                }
              });
            }
          });
          this.timeArr = data;
        });
      // appointTime(formData).then(res=>{
      //   this.timeArr=res.data.data;
      //   if(res.data.code==200){
      //     this.timeArr=res.data.data;
      //   }
      // })
    },
    searchTechnology() {
      const that = this;
      this.$axios.get(`http://localhost:9990/technology-meirong`)
        .then(response => {
          that.meirongList = response.data;
        });
    }
  }
};
</script>

<style scoped>


/* 搜索框 */
.search-input {
  display: inline-block;
  width: 1230px; /* 调整宽度 */
  margin-bottom: 20px;
}

/* 搜索容器 */
.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 表格样式 */
.el-table {
  margin-top: 20px;
}

/* 分页样式 */
.el-pagination {
  margin-top: 20px;
  text-align: center;
}

/* 表单容器 */
.form-container {
  margin-top: 20px;
}

<
style scoped >
.top_style, .top_active {
  border: 1px solid #AAA;
  padding: 3px 20px;
  text-align: center;
}

.top_active {
  border-color: #02A7F0;
  color: #02A7F0;
}

.button_style {
  text-align: center;
  float: left;
  width: 100px;
}


.payCompany_date {
  width: 400px;
  margin: 0 10px 10px 0;
}

.button_wrap .el-button {
  text-align: center;
  float: left;
  margin: 0 10px 10px 0;
}

.button_wrap .el-button:first-child {
  margin-left: 10px;
}
</style>
